#include <cstdio>
#include <algorithm>
#include <cstring>
#define _clr(x,a) memset(x,a,sizeof(x));
using namespace std;
char w[105];
char num[105];
char res[105];
int pb;
int sum;
int _max;
char te[10][5]={{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}};
struct Node{
    int p;
    Node* Next[26];
    char ch[105];
    Node(){
        p=0;
        for(int i=0;i<26;i++){
            Next[i]=NULL;
        }
    }
};
Node* root;
void insert(char* s,int pro){
    int val;
    char str[105];
    Node* p=root;
    for(int i=0;s[i];i++){
        val=s[i]-'a';
        if(p->Next[val]==NULL){
            p->Next[val]=new Node();
        }
        p=p->Next[val];
        p->p+=pro;
        str[i]=s[i];
        str[i+1]='\0';
        //保存到该节点的字符串
        strcpy(p->ch,str);
    }
}
void dfs(Node* po,int cur,int t){
    if(cur==t){
        if(po->p>_max){
            strcpy(res,po->ch);
            _max=po->p;
        }
        return;
    }
    int v=num[cur+1]-'0';
    //printf("v:%d\n",v);
    int l=strlen(te[v-2]);
    for(int i=0;i<l;i++){
        int val=te[v-2][i]-'a';
        //printf("%c\n",te[v-2][i]);
        if(po->Next[val]==NULL){
            continue;
        }
        else{
            //printf("dfs %d %c\n",val,'a'+val);
            dfs(po->Next[val],cur+1,t);
        }
    }
}
void clear(Node* root){
    if(root==NULL){
        return;
    }
    else{
        for(int i=0;i<26;i++){
            clear(root->Next[i]);
        }
    }
    delete(root);
}
int main(void){
    //freopen("data.txt","r",stdin);
    int t;
    scanf("%d",&t);
    for(int c=1;c<=t;c++){
        root=new Node();
        int n;
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            scanf("%s %d",w,&pb);
            insert(w,pb);
        }
        printf("Scenario #%d:\n",c);
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            scanf("%s",num);
            int l=strlen(num);
            for(int j=0;j<l-1;j++){
                _max=-1;
                dfs(root,-1,j);
                if(_max==-1){
                    printf("MANUALLY\n");
                }
                else{
                    printf("%s\n",res);
                }
            }
            if(i!=n-1){
                printf("\n");
            }
        }
        printf("\n\n");
        //clear(root);
    }
    return 0;
}
